package com.alogic.commonmark.reattr;

import com.alogic.commonmark.AbstractAttributeProvider;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.Script;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.util.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.commonmark.node.Node;
import org.commonmark.renderer.html.AttributeProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于logiclet的reattr插件
 *
 * @since 1.6.13.11 [20200901 duanyy]
 */
public class ReAttributeProvider extends AbstractAttributeProvider implements Configurable, XMLConfigurable {
    /**
     * a logger of slf4j
     */
    protected final Logger LOG = LoggerFactory.getLogger(ReAttributeProvider.class);

    /**
     * 针对的tag对象
     */
    protected String targetTag;

    /**
     * 事件处理
     */
    protected Logiclet event;

    protected String objectId = "$md-reattr";

    public ReAttributeProvider(){

    }

    @Override
    public void setAttribute(Node node, String tag, Map<String, String> map, Properties ctx) {
        if (tag.equals(targetTag)){
            if (event != null){
                LogicletContext logicletContext = new LogicletContext(ctx);
                try {
                    logicletContext.setObject(objectId, map);
                    logicletContext.SetValue("$tag",tag);
                    XsObject doc = new JsonObject("root",new HashMap<String,Object>());
                    event.execute(doc,doc, logicletContext, null);
                }catch (Exception ex){
                    LOG.info("Failed to execute onload script" + ExceptionUtils.getStackTrace(ex));
                }finally{
                    logicletContext.removeObject(objectId);
                }
            }
        }
    }

    @Override
    public void configure(Properties p) {
        targetTag = PropertiesConstants.getString(p,"tag","");
        objectId = PropertiesConstants.getString(p,"cid",objectId);
    }

    @Override
    public void configure(Element root, Properties p) {
        XmlElementProperties props = new XmlElementProperties(root,p);
        configure(props);
        try {
            event = Script.create(root, props);
        }catch (Exception ex){
            LOG.warn("Failed to create script:" + XmlTools.node2String(root));
        }
    }
}
